<template>
  <NModal :show="visible" title="资产统计" preset="card" class="w-900px" @update:show="emit('update:visible', $event)">
    <NSpin :show="loading">
      <NGrid :x-gap="12" :y-gap="12" :cols="4">
        <!-- 统计卡片 -->
        <NGi>
          <NStatistic label="总资产数" :value="statistics?.totalCount || 0">
            <template #prefix>
              <icon-mdi-database class="text-primary" />
            </template>
          </NStatistic>
        </NGi>
        <NGi>
          <NStatistic label="已发布" :value="statistics?.publishedCount || 0">
            <template #prefix>
              <icon-mdi-check-circle class="text-success" />
            </template>
          </NStatistic>
        </NGi>
        <NGi>
          <NStatistic label="草稿" :value="statistics?.draftCount || 0">
            <template #prefix>
              <icon-mdi-file-document-edit class="text-warning" />
            </template>
          </NStatistic>
        </NGi>
        <NGi>
          <NStatistic label="已归档" :value="statistics?.archivedCount || 0">
            <template #prefix>
              <icon-mdi-archive class="text-info" />
            </template>
          </NStatistic>
        </NGi>
      </NGrid>

      <NDivider />

      <!-- 图表 -->
      <NGrid :x-gap="12" :y-gap="12" :cols="2">
        <NGi>
          <NCard title="按类型统计" :bordered="false">
            <div ref="typeChartRef" style="height: 300px"></div>
          </NCard>
        </NGi>
        <NGi>
          <NCard title="按分级统计" :bordered="false">
            <div ref="levelChartRef" style="height: 300px"></div>
          </NCard>
        </NGi>
        <NGi :span="2">
          <NCard title="按分类统计" :bordered="false">
            <div ref="categoryChartRef" style="height: 300px"></div>
          </NCard>
        </NGi>
      </NGrid>
    </NSpin>
  </NModal>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import type { AssetStatistics } from '@/service/api/dataplatform/asset';
import { getAssetStatistics } from '@/service/api/dataplatform/asset';
import { useLoading } from '@sa/hooks';

interface Props {
  visible: boolean;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  'update:visible': [visible: boolean];
}>();

const { loading, startLoading, endLoading } = useLoading(false);
const statistics = ref<AssetStatistics | null>(null);

const typeChartRef = ref<HTMLElement>();
const levelChartRef = ref<HTMLElement>();
const categoryChartRef = ref<HTMLElement>();

let typeChart: echarts.ECharts | null = null;
let levelChart: echarts.ECharts | null = null;
let categoryChart: echarts.ECharts | null = null;

watch(
  () => props.visible,
  async val => {
    if (val) {
      await loadStatistics();
      await nextTick();
      initCharts();
    } else {
      disposeCharts();
    }
  }
);

async function loadStatistics() {
  startLoading();
  try {
    const { data } = await getAssetStatistics();
    statistics.value = data;
  } catch (error) {
    window.$message?.error('加载统计信息失败');
  } finally {
    endLoading();
  }
}

function initCharts() {
  if (!statistics.value) return;

  // 类型统计图表
  if (typeChartRef.value) {
    typeChart = echarts.init(typeChartRef.value);
    const typeData = Object.entries(statistics.value.typeCount || {}).map(([name, value]) => ({
      name: getTypeName(name),
      value
    }));
    typeChart.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: typeData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    });
  }

  // 分级统计图表
  if (levelChartRef.value) {
    levelChart = echarts.init(levelChartRef.value);
    const levelData = Object.entries(statistics.value.levelCount || {}).map(([name, value]) => ({
      name: getLevelName(name),
      value
    }));
    levelChart.setOption({
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          type: 'pie',
          radius: '50%',
          data: levelData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }
      ]
    });
  }

  // 分类统计图表
  if (categoryChartRef.value) {
    categoryChart = echarts.init(categoryChartRef.value);
    const categoryData = Object.entries(statistics.value.categoryCount || {});
    categoryChart.setOption({
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      xAxis: {
        type: 'category',
        data: categoryData.map(([name]) => name)
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          type: 'bar',
          data: categoryData.map(([, value]) => value),
          itemStyle: {
            color: '#18a058'
          }
        }
      ]
    });
  }
}

function disposeCharts() {
  typeChart?.dispose();
  levelChart?.dispose();
  categoryChart?.dispose();
  typeChart = null;
  levelChart = null;
  categoryChart = null;
}

function getTypeName(type: string): string {
  const typeMap: Record<string, string> = {
    TABLE: '数据表',
    VIEW: '视图',
    API: 'API',
    REPORT: '报表'
  };
  return typeMap[type] || type;
}

function getLevelName(level: string): string {
  const levelMap: Record<string, string> = {
    PUBLIC: '公开',
    INTERNAL: '内部',
    CONFIDENTIAL: '机密',
    SECRET: '绝密'
  };
  return levelMap[level] || level;
}
</script>
